package download.itydl.com.sinlethread.mutilthread.services;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;

import download.itydl.com.sinlethread.mutilthread.bean.FileInfo;

public class DownloadService extends Service {

    public static final int runThreadCount = 3;

    private static final String TAG = "DownloadService2";
    /**
     * Activity往Service传递Intent设置key
     */
    public static final String FILE_INFO = "fileInfo";
    /**
     * 开始下载
     */
    public static final String ACTION_START = "ACTION_START_2";
    /**
     * 暂停下载
     */
    public static final String ACTION_PAUSE = "ACTION_PAUSE_2";
    /**
     * 结束下载
     */
    public static final String ACTION_FINISHED = "ACTION_FINISHED_2";
    /**
     * 更新UI
     */
    public static final String ACTION_UPDATE = "ACTION_UPDATE_2";
    /**
     * 下载路径
     */
    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads2/";

    private HashMap<Integer, DownLoadTask> downLoadTasks = new LinkedHashMap<>();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if (ACTION_START.equals(action)) {
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(FILE_INFO);
            // 开始下载
            Log.e(TAG, fileInfo.toString());
            new InitTask(fileInfo).start();
        } else if (ACTION_PAUSE.equals(action)) {
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(FILE_INFO);
            // 暂停
            Log.e(TAG, fileInfo.toString());
            DownLoadTask downLoadTask = downLoadTasks.get(fileInfo.getId());
            if(downLoadTask != null){
                downLoadTask.isPause = true;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            FileInfo fileInfo = (FileInfo) msg.obj;
            Log.e(TAG, "handleMessage" + fileInfo.toString());
            DownLoadTask downLoadTask = new DownLoadTask(DownloadService.this, fileInfo, runThreadCount);
            downLoadTask.downLoad();
            downLoadTasks.put(fileInfo.getId(), downLoadTask);
        }
    };

    /**
     * 初始化线程信息（获取文件）
     */
    class InitTask extends Thread {

        private FileInfo fileInfo;

        public InitTask(FileInfo fileInfo) {
            this.fileInfo = fileInfo;
        }

        @Override
        public void run() {
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            try {
                URL url = new URL(fileInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                int length = -1;
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    length = conn.getContentLength();
                }

                if (length < 0) {
                    return;
                }

                fileInfo.setLength(length);

                // 创建本地文件长度
                File dir = new File(DOWNLOAD_PATH);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(dir, fileInfo.getFileName());
                raf = new RandomAccessFile(file, "rwd");
                raf.setLength(length);

                // 使用Handler发送初始化完成，并把最新FileInfo信息传过去
                Message message = handler.obtainMessage();
                message.obj = fileInfo;
                message.sendToTarget();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (raf != null && conn != null) {
                        conn.disconnect();
                        raf.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
